package cn.yunyichina.provider.bed.thread;

import cn.yunyichina.provider.bed.dao.OutpatientMedicineRecordDao;
import cn.yunyichina.provider.bed.dao.OutpatientMedicineRecordListDao;
import cn.yunyichina.provider.bed.dao.OutpatientSummaryDao;
import cn.yunyichina.provider.bed.entity.MedicalCard;
import cn.yunyichina.provider.bed.entity.OutpatientMedicineRecord;
import cn.yunyichina.provider.bed.entity.OutpatientMedicineRecordList;
import cn.yunyichina.provider.bed.vo.BedVo;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.bed.MedicineDetail;
import cn.yunyichina.provider.iface.entity.hisiface.bed.MedicineItem;
import cn.yunyichina.provider.iface.entity.hisiface.bed.OutMedicineVoResponse;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zd on 2016/12/17.
 */
public class OutpatientMedicineRecordRunnable implements Runnable {
    private Logger logger = LoggerFactory.getLogger(OutpatientMedicineRecordRunnable.class);

    private  OutMedicineVoResponse outMedicine ;
    private BedVo requestVo;

    public OutpatientMedicineRecordRunnable(OutMedicineVoResponse outMedicine,BedVo requestVo) {
        this.outMedicine = outMedicine;
        this.requestVo = requestVo;
    }
    @Override
    public void run() {
        logger.info("保存出院带药记录开始======outMedicine ="+JsonUtils.toJsonString(outMedicine));

        OutpatientMedicineRecordDao outMedicineRecordDao = SpringContextHandler.getBean(OutpatientMedicineRecordDao.class);
        OutpatientMedicineRecord outMedicineRecord = outMedicineRecordDao.selectByAdmissionNoAndPatientId(requestVo.getAdmissionNo(),requestVo.getPatientId(),requestVo.getHospitalCode());
        MedicalCard medicalCard = null;
        if (StringUtils.isNotBlank(requestVo.getMedicalCardId())){
            //查询绑定卡
            JSONObject medicalParam = new JSONObject();
            medicalParam.put("id", requestVo.getMedicalCardId());
            logger.info("【出院带药保存线程处理-查询绑定卡信息】, yyt.base.medicalcard.by.id.get request=" + JSON.toJSONString(medicalParam));
            Response medicalResponse = BaseService.callHumpFromInternal("yyt.base.medicalcard.by.id.get", JsonUtils.toJsonString(medicalParam));
            logger.info("【出院带药保存线程处理-查询绑定卡信息】, yyt.base.medicalcard.by.id.get response=" + JSONObject.toJSONString(medicalResponse));
            if (!"0".equals(medicalResponse.getResultCode())) {
                throw new CallException("14010","找不到绑定卡信息 by id=" + requestVo.getMedicalCardId());
            }
            medicalCard = JsonUtils.parseObject(medicalResponse.getResult(), MedicalCard.class);

        }

        // 查询组织信息-----------------------------------------------start
        Map<String, String> orgParamMap = new HashMap<String, String>();
        orgParamMap.put("org_code", requestVo.getHospitalCode());
        logger.info("【出院带药-查询组织信息】, yyt.base.branchhospital.org.list request=" + JSON.toJSONString(orgParamMap));
        Response orgResponse = BaseService.callUnderlineFromInternal("yyt.base.branchhospital.org.list", JSON.toJSONString(orgParamMap));
        logger.info("【出院带药-查询组织信息】, yyt.base.branchhospital.org.list response=" + JSONObject.toJSONString(orgResponse));
        if (!"0".equals(orgResponse.getResultCode())) {
            throw new CallException("14010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        List<Org> orgList = JsonUtils.parseArray(orgResponse.getResult(), Org.class);
        if (org.springframework.util.CollectionUtils.isEmpty(orgList)) {
            throw new CallException("14010","找不到机构信息 by org_code=" + requestVo.getHospitalCode());
        }
        Org org = orgList.get(0);

        if (outMedicineRecord == null){
            logger.info("保存");
            outMedicineRecord = new OutpatientMedicineRecord();
            outMedicineRecord.setId(PKGenerator.generateId());
            outMedicineRecord.setAdmissionNo(requestVo.getAdmissionNo());
            outMedicineRecord.setOrgCode(requestVo.getHospitalCode());
            outMedicineRecord.setInpatientId(requestVo.getPatientId());
            outMedicineRecord.setInTime(Integer.valueOf(requestVo.getInTime()));
            outMedicineRecord.setBranchId("");
            outMedicineRecord.setBranchCode("");
            outMedicineRecord.setBranchName("");
            outMedicineRecord.setPatName(medicalCard==null?"":medicalCard.getPatName());
            outMedicineRecord.setPatId(medicalCard==null?"":medicalCard.getPatId());
            outMedicineRecord.setDeptCode("");
            outMedicineRecord.setDeptName(outMedicine.getDeptName());
            outMedicineRecord.setOrgId(org.getId());
            outMedicineRecord.setOrgName(org.getOrgName());

            outMedicineRecord.setCreatedTime(DateUtils.getDatetime());

            outMedicineRecordDao.insert(outMedicineRecord);
        }
        OutpatientMedicineRecordListDao outMedicineRecordListDao = SpringContextHandler.getBean(OutpatientMedicineRecordListDao.class);

        List<OutpatientMedicineRecordList> outMedRecordLists = outMedicineRecordListDao.selectByMedicineRecordId(outMedicineRecord.getId());
        //数据库中没有记录
        if(CollectionUtils.isEmpty(outMedRecordLists)&& CollectionUtils.isNotEmpty(outMedicine.getMedicineItems())){
            List<OutpatientMedicineRecordList> outMedRecordListToSave = new ArrayList<>();
            List<MedicineItem> medicineItems = outMedicine.getMedicineItems();
            for (MedicineItem medicineItem :medicineItems){
                List<MedicineDetail> medicineDetails = medicineItem.getMedicineDetails();
                if (CollectionUtils.isNotEmpty(medicineDetails)){
                    for (MedicineDetail medicineDetail:medicineDetails){
                        OutpatientMedicineRecordList outMedRecordList = new OutpatientMedicineRecordList();
                        outMedRecordList.setId(PKGenerator.generateId());
                        //外键
                        outMedRecordList.setOutpatientMedicineRecordId(outMedicineRecord.getId());
                        outMedRecordList.setDrugType(medicineItem.getDrugType());
                        outMedRecordList.setCommonName(medicineDetail.getCommonName());
                        outMedRecordList.setDrugCode(medicineDetail.getDrugCode());
                        outMedRecordList.setGoodsName(medicineDetail.getGoodsName());
                        outMedRecordList.setItemFrequency(medicineDetail.getItemFrequency());
                        outMedRecordList.setItemSpec(medicineDetail.getItemSpec());
                        outMedRecordList.setItemTotal(Integer.parseInt(medicineDetail.getItemTotal()));
                        outMedRecordList.setItemUnit(medicineDetail.getItemUnit());
                        outMedRecordList.setItemUsage(medicineDetail.getItemUsage());
                        outMedRecordList.setNoticeDesc(medicineDetail.getNoticeDesc());
                        outMedRecordList.setSingleDose(medicineDetail.getSingleDose());
                        outMedRecordListToSave.add(outMedRecordList);
                    }
                }
            }
            if(CollectionUtils.isNotEmpty(outMedRecordListToSave)){
                outMedicineRecordListDao.batchInsert(outMedRecordListToSave);
            }

        }
    }
}
